package app.fugema.shop.main.order.view;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.RecyclerView;
import app.fugema.shop.main.goods.model.GoodsDetailResult;
import app.fugema.shop.main.goods.model.SkuBean;
import app.fugema.shop.main.goods.model.SkuPriceBean;
import app.fugema.shop.main.goods.model.SkuPriceResult;
import app.fugema.shop.main.order.adapter.ShoppingSpecificationItemAdapter;
import app.fugema.shop.main.order.model.ShopCartProduct;
import app.fugema.shop.main.order.model.ShoppingSubmitInfo;

import com.base.common.app.BaseConstant;
import com.base.common.app.LoginUtils;
import com.base.common.model.http.jackSon.JacksonUtils;
import com.base.common.netBeanPackage.BaseApiResult;
import com.base.common.netBeanPackage.LiveDataWrapper;
import com.base.common.utils.DensityUtil;
import com.base.common.utils.LogUtil;
import com.base.common.utils.OnClickCheckedUtil;
import com.base.common.utils.UIUtils;
import com.base.common.view.adapter.MyFlexboxLayoutManager;
import com.base.common.view.adapter.ada.BaseRVAdapter;
import com.base.common.view.base.BaseDialogFragment;
import com.base.common.viewmodel.BaseViewObserver;
import com.jeremyliao.liveeventbus.LiveEventBus;
import app.fugema.shop.R;
import app.fugema.shop.databinding.ShoppingSpecificationFragmentBinding;

import app.fugema.shop.main.order.vm.ShoppingCartVM;

import java.util.ArrayList;
import java.util.List;

public class ShoppingSpecificationDialog extends BaseDialogFragment<ShoppingSpecificationFragmentBinding, ShoppingCartVM> {

    public static ShoppingSpecificationDialog getInstance(@NonNull GoodsDetailResult dataBean, boolean isUpdateSku)
    {
        ShoppingSpecificationDialog shoppingCartBottomFragment = new ShoppingSpecificationDialog();
        Bundle args = new Bundle();
        args.putString("data", JacksonUtils.transBean2Json(dataBean));
        args.putBoolean("isUpdateSku", isUpdateSku);
        shoppingCartBottomFragment.setArguments(args);
        return shoppingCartBottomFragment;
    }

    @Override
    protected ShoppingSpecificationFragmentBinding initDataBinding(LayoutInflater inflater, ViewGroup container)
    {
        return DataBindingUtil.inflate(inflater, R.layout.shopping_specification_fragment, container, false);
    }

    private GoodsDetailResult dataBean;

    private ShoppingSpecificationItemAdapter specificationItemAdapter;

    private ShoppingSpecificationItemAdapter specSizeAdapter;

    private ShoppingSpecificationItemAdapter specVersionAdapter;

    //是否修改规格
    private boolean isUpdateSku;
    //修改规格的返回
    private OnResultShoppingCartSku onResultShoppingCartSku;

    private long count = 1;

    public void setOnResultShoppingCartSku(OnResultShoppingCartSku onResultShoppingCartSku)
    {
        this.onResultShoppingCartSku = onResultShoppingCartSku;
    }
    // 选中的 规格
    private SkuBean colorSku;
    private SkuBean sizeSku;
    private SkuBean versionSku;
    // 保存各规格的 价格、库存等
    private List<SkuPriceBean> skuPriceList;
    private SkuPriceBean selectSkuPrice;

    private String userKey = "";
    @Override
    protected void initNotificationReceipt()
    {
        super.initNotificationReceipt();
        LiveEventBus.get(BaseConstant.EventKey.PAY_SUCCESS, String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String o)
            {
                LogUtil.e( "商品信息页选择规格关闭_订单 = " + o );
                //支付成功后关闭
                dismissAllowingStateLoss();
            }
        });
    }

    @Override
    public void initView()
    {
        super.initView();
        dataBean = JacksonUtils.getJsonBean(getArguments().getString("data", null), GoodsDetailResult.class);
        isUpdateSku = getArguments().getBoolean("isUpdateSku", false);
        skuPriceList = new ArrayList<>();
        if (isUpdateSku)
        {
            binding.rtvAddCart.setVisibility(View.GONE);
            binding.rtvPay.setVisibility(View.GONE);
            binding.rtvOK.setVisibility(View.VISIBLE);
            binding.llPayCount.setVisibility(View.INVISIBLE);
            binding.vLine3.setVisibility(View.GONE);
        }

        if (dataBean != null)
        {
            if(UIUtils.isNotEmpty( dataBean.getProductJson() ))
            {
                GoodsDetailResult.SimpleProduct simpleProduct = JacksonUtils.getJsonBean(dataBean.getProductJson() ,GoodsDetailResult.SimpleProduct.class);
                binding.tvPrice.setText( simpleProduct.getPrice() );
                binding.setItem(simpleProduct);
            }
            // 颜色
            specificationItemAdapter = new ShoppingSpecificationItemAdapter()
            {
                @Override
                public void onItemClick(View view, BaseRVAdapter adapter, int onclickType, int position, SkuBean bean)
                {
                    super.onItemClick(view, adapter, onclickType, position, bean);

                    //选择的规格  颜色
                    colorSku = bean;
                    //显示规格
                    setSelectSkuText(colorSku,sizeSku,versionSku);
                    String skuIdStr =  getSelectSkuId(dataBean.getProduct(),colorSku,sizeSku,versionSku);

                    selectSkuPrice = getSelectSkuPrice(skuIdStr,skuPriceList);
                    //显示价格 库存
                    setSelectPriceStockText(selectSkuPrice);
                }
            };
            // 尺码
            specSizeAdapter = new ShoppingSpecificationItemAdapter()
            {
                @Override
                public void onItemClick(View view, BaseRVAdapter adapter, int onclickType, int position, SkuBean bean)
                {
                    super.onItemClick(view, adapter, onclickType, position, bean);
                    //选择的规格
                    sizeSku = bean;
                    //显示规格
                    setSelectSkuText(colorSku,sizeSku,versionSku);
                    String skuIdStr =  getSelectSkuId(dataBean.getProduct(),colorSku,sizeSku,versionSku);

                    selectSkuPrice = getSelectSkuPrice(skuIdStr,skuPriceList);
                    //显示价格 库存
                    setSelectPriceStockText(selectSkuPrice);
                }
            };
            // 规格
            specVersionAdapter = new ShoppingSpecificationItemAdapter()
            {
                @Override
                public void onItemClick(View view, BaseRVAdapter adapter, int onclickType, int position, SkuBean bean)
                {
                    super.onItemClick(view, adapter, onclickType, position, bean);
                    //选择的规格
                    versionSku = bean;
                    //显示规格
                    setSelectSkuText(colorSku,sizeSku,versionSku);
                    String skuIdStr =  getSelectSkuId(dataBean.getProduct(),colorSku,sizeSku,versionSku);

                    selectSkuPrice = getSelectSkuPrice(skuIdStr,skuPriceList);
                    //显示价格 库存
                    setSelectPriceStockText(selectSkuPrice);
                }
            };

            //单选
            specificationItemAdapter.setRadio(true);
            binding.rvRecyclerView.setLayoutManager(new MyFlexboxLayoutManager(getActivity()));
            binding.rvRecyclerView.setAdapter(specificationItemAdapter);
            if (UIUtils.isNotEmpty(dataBean.getColor()))
            {
                //找出库存不为0的规格  已选择或第一个，  不管库存
                SkuBean skuFirst = null;
                // 颜色
                //SkuBean skuListBean : dataBean.getColor()
                for (int i = 0 ; i < dataBean.getColor().size();i++ )
                {
                    skuFirst = dataBean.getColor().get(0);
                    /*
                    if (skuListBean.getEnabledClass().equals("enabled") )
                    {
                        if (skuFirst == null)
                        {
                            skuFirst = skuListBean;
                        }
                        if (skuListBean.getSelected())
                        {
                            skuFirst = skuListBean;
                            break;
                        }
                    }
                    */
                }
                if (skuFirst != null)
                {
                    colorSku = skuFirst;
                    skuFirst.setSelected(true);
                }
                binding.tvSpecificationText.setText( dataBean.getColorAlias() );
                specificationItemAdapter.setDataList(dataBean.getColor());
            }
            else
            {
                //没有  颜色
                binding.llSpecColor.setVisibility(View.GONE);
            }

            if (UIUtils.isNotEmpty(dataBean.getSize()))
            {
                SkuBean skuFirstSize = null;
                // 颜色
                for (int j= 0 ; j < dataBean.getSize().size() ; j++ )
                {
                    skuFirstSize = dataBean.getSize().get(0);
                }
                if( skuFirstSize != null  )
                {
                    sizeSku = skuFirstSize;
                }
                LogUtil.e("默认size_version skuid =" + sizeSku.getSkuId());
            }
            // 设置尺寸
            setSpecListView(specSizeAdapter,binding.rvRecyclerView2,dataBean.getSize(),binding.tvSpecSizeTag,dataBean.getSizeAlias(),binding.llSpecSize);
            if (UIUtils.isNotEmpty(dataBean.getVersion()))
            {
                SkuBean skuFirstVersion = null;
                for (int j= 0 ; j < dataBean.getVersion().size() ; j++ )
                {
                    skuFirstVersion = dataBean.getVersion().get(0);
                }
                if( skuFirstVersion != null  )
                {
                    versionSku = skuFirstVersion;
                }
                LogUtil.e("默认size_version skuid =" + versionSku.getSkuId());
            }

            //设置 规格
            setSpecListView(specVersionAdapter,binding.rvRecyclerView3,dataBean.getVersion(),binding.tvSpecVersionTag,dataBean.getVersionAlias(),binding.llSpecVersion);

            //查询该商品各规格价格等
            if( LoginUtils.isLogin() )
            {
                userKey = LoginUtils.getToken();
            }
            viewModel.getSkuInfo(dataBean.getProduct().getProductId() , userKey)
                     .observe(this, new BaseViewObserver<LiveDataWrapper<SkuPriceResult>>()
                     {
                         @Override
                         protected void onSuccess(LiveDataWrapper<SkuPriceResult> data)
                         {
                             //LogUtil.e("查询规格明细");
                             if( data.data.isSuccess() )
                             {
                                 skuPriceList.clear();
                                 skuPriceList.addAll(data.data.getSkuArray());

                                 if( UIUtils.isNotEmpty(colorSku) )
                                 {
                                     LogUtil.e("ColorSkuId = " + colorSku.getSkuId());
                                 }
                                 else
                                 {
                                     LogUtil.e("ColorSku = 空");
                                 }
                                 if( UIUtils.isNotEmpty(sizeSku) )
                                 {
                                     LogUtil.e("sizeSkuId = " + sizeSku.getSkuId());
                                 }
                                 else
                                 {
                                     LogUtil.e("sizeSku = 空");
                                 }
                                 if( UIUtils.isNotEmpty(versionSku) )
                                 {
                                     LogUtil.e("versionSkuId = " + versionSku.getSkuId());
                                 }
                                 else
                                 {
                                     LogUtil.e("versionSku = 空");
                                 }
                                 //显示默认规格
                                 setSelectSkuText(colorSku,sizeSku,versionSku);
                                 String skuIdStr =  getSelectSkuId(dataBean.getProduct(),colorSku,sizeSku,versionSku);

                                 selectSkuPrice = getSelectSkuPrice(skuIdStr,skuPriceList);
                                 //显示价格 库存
                                 setSelectPriceStockText(selectSkuPrice);
                             }
                         }
                     });

        }
        // 添加的 数量
        binding.rtvGoodsCount.setText(  String.valueOf( count ) );

        // 按钮点击事件
        binding.setOnClickCheckedUtil(new OnClickCheckedUtil()
        {
            @Override
            public void onClicked(View view)
            {
                if (dataBean == null ) return;
                //color
                SkuBean skuListBean = specificationItemAdapter.getSelectBean();

                switch (view.getId())
                {
                    //关闭
                    case R.id.btn_close_dialog:
                        dismissAllowingStateLoss();
                        break;
                    // 数量 减
                    case R.id.ivGoodsReduce:

                        doNumLogic(false ,binding.rtvGoodsCount);
                        //if (dataBean.getPayCount() > 1) {dataBean.setPayCount(dataBean.getPayCount() - 1);}
                        break;
                    // 数量 加
                    case R.id.ivGoodsAdd:
                        // 选中的 规格
                        if (UIUtils.isNotEmpty(selectSkuPrice))
                        {
                            if ( selectSkuPrice.getStock() > count +1)
                            {
                                doNumLogic(true ,binding.rtvGoodsCount);
                            }
                            else
                            {
                                UIUtils.showToastSafesClose("库存不足");
                            }
                        }
                        break;
                    case R.id.rtvAddCart:
                        if (!LoginUtils.isLogin())
                        {
                            UIUtils.showToastSafes("未登录请登录");
                            LoginUtils.loginIn();
                            return;
                        }
                        if (skuListBean == null)
                        {
                            UIUtils.showToastSafesClose("请选择商品的规格");
                            return;
                        }

                        userKey = LoginUtils.getToken();

                        // 添加到 购物车
                        String skuIdStr =  getSelectSkuId(dataBean.getProduct(),colorSku,sizeSku,versionSku);
                        addShoppingCart(skuIdStr,(int)count,userKey);
                        break;
                    case R.id.rtvPay:
                        if (!LoginUtils.isLogin())
                        {
                            UIUtils.showToastSafes("未登录请登录");
                            LoginUtils.loginIn();
                            return;
                        }

                        if (skuListBean == null)
                        {
                            UIUtils.showToastSafesClose("请选择商品的规格");
                            return;
                        }
                        //直接购买
                        ShoppingSubmitInfo orderInfo = new ShoppingSubmitInfo();
                        orderInfo.setBuyNow(true);
                        orderInfo.setCounts(""+count);
                        String skuTempStr = getSelectSkuId(dataBean.getProduct(),colorSku,sizeSku,versionSku);
                        orderInfo.setIdStr(skuTempStr);
                        orderInfo.setProducttype( dataBean.getProductType() );
                        ShoppingConfirmOrderActivity.start(view.getContext(), orderInfo);

                        break;
                    case R.id.rtvOK:
                        // 确定 按钮  不知道 干什么的
                        if (skuListBean == null)
                        {
                            UIUtils.showToastSafesClose("请选择商品的规格");
                            return;
                        }
                        if (onResultShoppingCartSku != null)
                        {
                            ShopCartProduct bean = new ShopCartProduct();
                            //bean.setProdCount(dataBean.getPayCount());
                            bean.setSkuId(""+skuListBean.getSkuId());
                            //bean.setSkuName(skuListBean.getSkuName());
                            onResultShoppingCartSku.onResultCartSku(bean);
                        }
                        dismissAllowingStateLoss();
                        break;
                }
            }
        });
    }

    /**  获取拼接后的 skuId
     * @param product
     * @param mColorSku
     * @param mSizeSku
     * @param mVersionSku
     * @return
     */
    private String getSelectSkuId(GoodsDetailResult.ProductBean product,SkuBean mColorSku,SkuBean mSizeSku,SkuBean mVersionSku)
    {
        StringBuffer skuSb = new StringBuffer();
        skuSb.append(product.getProductId()).append("_");
        if( UIUtils.isNotEmpty( mColorSku ) )
        {
            skuSb.append(mColorSku.getSkuId()).append("_");
        }
        else
        {
            skuSb.append(0).append("_");
        }
        if( UIUtils.isNotEmpty( mSizeSku ) )
        {
            skuSb.append(mSizeSku.getSkuId()).append("_");
        }
        else
        {
            skuSb.append(0).append("_");
        }
        if( UIUtils.isNotEmpty( mVersionSku ) )
        {
            skuSb.append(mVersionSku.getSkuId());
        }
        else
        {
            skuSb.append(0);
        }
        LogUtil.e("skuStr = "+ skuSb.toString());
        return skuSb.toString();
    }

    private void doNumLogic(boolean isAdd , TextView editNumTv )
    {
        String numS = editNumTv.getText().toString().trim();
        if (TextUtils.isEmpty(numS))
        {
            editNumTv.setText("1");
            return;
        }
        long num = Long.valueOf(numS);
        if (isAdd)
        {
            num++;
        }
        else
        {
            if (num <= 1) num = 1;
            else
                num--;
        }
        count = num;
        editNumTv.setText(num + "");
    }

    //添加到购物车
    private void addShoppingCart( String skuId,int count,String userKey)
    {

        viewModel.addGoodsToCart(skuId, count,userKey).observe(this, new BaseViewObserver<LiveDataWrapper<BaseApiResult>>(this) {
            @Override
            protected void onSuccess(LiveDataWrapper<BaseApiResult> data) {
                UIUtils.showToastSafes("已添加到购物车");
                dismissAllowingStateLoss();
            }
        });
    }

    @Override
    protected int getHeight()
    {
        return DensityUtil.getDimens(R.dimen.dp_500);
    }

    // 设置 各种规格
    private void setSpecListView(ShoppingSpecificationItemAdapter itemAdapter, RecyclerView mRv, List<SkuBean> specSkuList, TextView  specTagTv , String specAlias, LinearLayout rootGroupView)
    {
        //单选
        itemAdapter.setRadio(true);
        mRv.setLayoutManager(new MyFlexboxLayoutManager(getActivity()));
        mRv.setAdapter(itemAdapter);
        if (UIUtils.isNotEmpty(specSkuList))
        {
            //找出库存不为0的规格  已选择或第一个，  不管库存  就选 第一个
            SkuBean skuFirstTemp = null;
            // 颜色
            //SkuBean skuListBean : specSkuList
            for (int j= 0 ; j < specSkuList.size() ; j++ )
            {
                skuFirstTemp = specSkuList.get(0);
                /*
                if (skuListBean.getEnabledClass().equals("enabled") )
                {
                    if (skuFirst == null)
                    {
                        skuFirst = skuListBean;
                    }
                    if (skuListBean.getSelected())
                    {
                        skuFirst = skuListBean;
                        break;
                    }
                }
                else
                {
                    // 没库存 不能选
                    // 这里 需要 修改
                    skuListBean.setChecked(false);
                }
                */
            }
            if (skuFirstTemp != null)
            {
                skuFirstTemp.setSelected(true);
            }
            specTagTv.setText( specAlias );
            itemAdapter.setDataList(specSkuList);
        }
        else
        {
            //没有  颜色
            rootGroupView.setVisibility(View.GONE);
        }
    }

    /**
     *  获取 选中的 规格
     * @param skuIdStr
     * @param mSkuPriceList
     * @return
     */
    private SkuPriceBean getSelectSkuPrice(String skuIdStr , List<SkuPriceBean> mSkuPriceList)
    {
        if( !mSkuPriceList.isEmpty() )
        {
            for (SkuPriceBean tempSkuPrice : mSkuPriceList)
            {
                if( tempSkuPrice.getSkuId().equals(skuIdStr) )
                {
                    return tempSkuPrice;
                }
            }
        }
        return null;
    }

    /**
     * 显示 选中的 规格
     * @param mColorSku
     * @param mSizeSku
     * @param mVersionSku
     */
    private void setSelectSkuText(SkuBean mColorSku,SkuBean mSizeSku,SkuBean mVersionSku)
    {
        StringBuffer sbr = new StringBuffer();
        if( UIUtils.isNotEmpty( mColorSku ) )
        {
            sbr.append( mColorSku.getValue() );
        }

        if( UIUtils.isNotEmpty( mSizeSku ) )
        {
            if( UIUtils.isNotEmpty( sbr.toString() ) )
            {
                sbr.append( "," );
            }
            sbr.append( mSizeSku.getValue() );
        }

        if( UIUtils.isNotEmpty( mVersionSku ) )
        {
            if( UIUtils.isNotEmpty( sbr.toString() ) )
            {
                sbr.append( "," );
            }
            sbr.append( mVersionSku.getValue() );
        }
        binding.tvSpecification.setText("已选规格：" + sbr.toString());
    }

    /**
     * 显示 选中的  价格 库存
     * @param mSkuPrice
     */
    private void setSelectPriceStockText(SkuPriceBean mSkuPrice )
    {
        if( UIUtils.isNotEmpty( mSkuPrice ) )
        {
            binding.tvPrice.setText('¥'+String.valueOf( mSkuPrice.getPrice() ));
            binding.tvStock.setText("库存："+String.valueOf( mSkuPrice.getStock() ));
        }
    }

    interface OnResultShoppingCartSku
    {
        void onResultCartSku(ShopCartProduct dataBean);
    }

}
